<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>贪吃蛇小游戏</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        snake: '#22c55e',
                        food: '#ef4444',
                        game: '#1e293b',
                    },
                }
            }
        }
    </script>

    <style type="text/tailwindcss">
        @layer utilities {
            .game-grid {
                background-size: calc(100% / 19) calc(100% / 19);
                background-image:
                    linear-gradient(to right, rgba(255,255,255,0.05) 1px, transparent 1px),
                    linear-gradient(to bottom, rgba(255,255,255,0.05) 1px, transparent 1px);
            }
            .control-btn {
                @apply w-12 h-12 md:w-16 md:h-16 rounded-lg flex items-center justify-center text-white text-xl md:text-2xl transition-all duration-150 active:scale-90 focus:outline-none;
            }
        }
    </style>
</head>
<body class="bg-gradient-to-br from-slate-900 to-slate-800 min-h-screen flex flex-col">
    <header class="bg-slate-800/80 backdrop-blur-sm border-b border-slate-700">
        <div class="container mx-auto px-4 py-4 flex justify-between items-center">
            <h1 class="text-2xl md:text-3xl font-bold text-white flex items-center">
                <i class="fa fa-gamepad mr-3 text-green-400"></i>贪吃蛇小游戏
            </h1>
            <div class="flex items-center space-x-4">
                <button id="fullscreen-toggle" class="text-white hover:text-green-400 transition-colors">
                    <i class="fa fa-expand text-xl"></i>
                </button>
            </div>
        </div>
    </header>

    <main class="flex-grow container mx-auto px-4 py-8 flex flex-col items-center justify-center">
        <div class="w-full max-w-2xl">
            <!-- 游戏信息面板 -->
            <div class="bg-slate-800/50 backdrop-blur-sm rounded-xl p-4 mb-6 border border-slate-700 shadow-lg">
                <div class="grid grid-cols-3 gap-4 text-center">
                    <div class="p-3 bg-slate-700/50 rounded-lg">
                        <p class="text-slate-300 text-sm mb-1">当前分数</p>
                        <p id="current-score" class="text-white text-2xl font-bold">0</p>
                    </div>
                    <div class="p-3 bg-slate-700/50 rounded-lg">
                        <p class="text-slate-300 text-sm mb-1">最高分</p>
                        <p id="high-score" class="text-green-400 text-2xl font-bold">0</p>
                    </div>
                    <div class="p-3 bg-slate-700/50 rounded-lg">
                        <p class="text-slate-300 text-sm mb-1">等级</p>
                        <p id="level" class="text-blue-400 text-2xl font-bold">1</p>
                    </div>
                </div>
            </div>

            <!-- 游戏区域 -->
            <div class="relative w-full aspect-square max-w-md mx-auto bg-game rounded-xl overflow-hidden shadow-2xl border-4 border-slate-700">
                <canvas id="gameCanvas" class="w-full h-full game-grid"></canvas>

                <!-- 开始游戏覆盖层 -->
                <div id="start-screen" class="absolute inset-0 bg-slate-900/80 backdrop-blur-sm flex flex-col items-center justify-center">
                    <h2 class="text-3xl font-bold text-white mb-6">贪吃蛇</h2>
                    <p class="text-slate-300 mb-8 text-center px-6">使用方向键或WASD控制蛇移动，吃到食物得分，撞到墙壁或自己则游戏结束</p>
                    <button id="start-btn" class="bg-green-600 hover:bg-green-500 text-white font-bold py-3 px-8 rounded-full text-lg transition-all duration-200 transform hover:scale-105">
                        开始游戏
                    </button>
                </div>

                <!-- 游戏结束覆盖层 -->
                <div id="game-over-screen" class="absolute inset-0 bg-slate-900/80 backdrop-blur-sm flex flex-col items-center justify-center hidden">
                    <h2 class="text-3xl font-bold text-red-500 mb-2">游戏结束</h2>
                    <p class="text-white text-xl mb-2">最终得分: <span id="final-score">0</span></p>
                    <p class="text-slate-300 mb-8">再接再厉！</p>
                    <button id="restart-btn" class="bg-green-600 hover:bg-green-500 text-white font-bold py-3 px-8 rounded-full text-lg transition-all duration-200 transform hover:scale-105">
                        重新开始
                    </button>
                </div>
            </div>

            <!-- 游戏控制按钮 (移动设备) -->
            <div class="md:hidden mt-8 grid grid-cols-3 gap-4 max-w-md mx-auto">
                <div class="col-start-2">
                    <button id="up-btn" class="control-btn bg-slate-700 hover:bg-slate-600">
                        <i class="fa fa-arrow-up"></i>
                    </button>
                </div>
                <div class="col-start-1 row-start-2">
                    <button id="left-btn" class="control-btn bg-slate-700 hover:bg-slate-600">
                        <i class="fa fa-arrow-left"></i>
                    </button>
                </div>
                <div class="col-start-2 row-start-2">
                    <button id="down-btn" class="control-btn bg-slate-700 hover:bg-slate-600">
                        <i class="fa fa-arrow-down"></i>
                    </button>
                </div>
                <div class="col-start-3 row-start-2">
                    <button id="right-btn" class="control-btn bg-slate-700 hover:bg-slate-600">
                        <i class="fa fa-arrow-right"></i>
                    </button>
                </div>
            </div>

            <!-- 游戏控制区 (桌面) -->
            <div class="hidden md:flex justify-center mt-8 space-x-4">
                <button id="pause-btn" class="bg-slate-700 hover:bg-slate-600 text-white px-5 py-2 rounded-lg transition-all">
                    <i class="fa fa-pause mr-2"></i>暂停
                </button>
                <button id="resume-btn" class="bg-green-600 hover:bg-green-500 text-white px-5 py-2 rounded-lg transition-all hidden">
                    <i class="fa fa-play mr-2"></i>继续
                </button>
                <button id="desktop-restart-btn" class="bg-red-600 hover:bg-red-500 text-white px-5 py-2 rounded-lg transition-all">
                    <i class="fa fa-refresh mr-2"></i>重新开始
                </button>
            </div>
        </div>
    </main>

    <footer class="bg-slate-800/80 backdrop-blur-sm border-t border-slate-700 py-4">
        <div class="container mx-auto px-4 text-center text-slate-400 text-sm">
            <p>使用键盘方向键或WASD控制蛇移动 | 吃到食物得分 | 撞到墙壁或自己则游戏结束</p>
        </div>
    </footer>

    <script>
        document.addEventListener('DOMContentLoaded', () => {
            // 获取DOM元素
            const canvas = document.getElementById('gameCanvas');
            const ctx = canvas.getContext('2d');
            const startScreen = document.getElementById('start-screen');
            const gameOverScreen = document.getElementById('game-over-screen');
            const startBtn = document.getElementById('start-btn');
            const restartBtn = document.getElementById('restart-btn');
            const desktopRestartBtn = document.getElementById('desktop-restart-btn');
            const pauseBtn = document.getElementById('pause-btn');
            const resumeBtn = document.getElementById('resume-btn');
            const currentScoreEl = document.getElementById('current-score');
            const highScoreEl = document.getElementById('high-score');
            const levelEl = document.getElementById('level');
            const finalScoreEl = document.getElementById('final-score');
            const fullscreenToggle = document.getElementById('fullscreen-toggle');
            const upBtn = document.getElementById('up-btn');
            const downBtn = document.getElementById('down-btn');
            const leftBtn = document.getElementById('left-btn');
            const rightBtn = document.getElementById('right-btn');

            // 设置画布尺寸
            const gridSize = 20; // 网格大小
            const tileCount = 20; // 每行/列的格子数
            canvas.width = gridSize * tileCount;
            canvas.height = gridSize * tileCount;

            // 游戏状态变量
            let snake = [];
            let food = {};
            let dx = gridSize; // 水平速度
            let dy = 0; // 垂直速度
            let nextDx = dx; // 下一次水平速度 (用于防止180度转向)
            let nextDy = dy; // 下一次垂直速度
            let score = 0;
            let highScore = localStorage.getItem('snakeHighScore') || 0;
            let level = 1;
            let gameLoop;
            let isGameRunning = false;
            let isPaused = false;
            let foodEatenInLevel = 0;

            // 更新高分显示
            highScoreEl.textContent = highScore;

            // 初始化游戏
            function initGame() {
                // 重置蛇的位置和长度
                snake = [
                    {x: gridSize * 10, y: gridSize * 10},
                    {x: gridSize * 9, y: gridSize * 10},
                    {x: gridSize * 8, y: gridSize * 10}
                ];

                // 重置速度
                dx = gridSize;
                dy = 0;
                nextDx = dx;
                nextDy = dy;

                // 重置分数和等级
                score = 0;
                level = 1;
                foodEatenInLevel = 0;

                // 更新UI
                currentScoreEl.textContent = score;
                levelEl.textContent = level;

                // 生成食物
                generateFood();

                // 隐藏游戏结束屏幕
                gameOverScreen.classList.add('hidden');

                // 重置游戏状态
                isGameRunning = true;
                isPaused = false;
            }

            // 生成食物位置
            function generateFood() {
                // 随机生成食物位置
                food = {
                    x: Math.floor(Math.random() * tileCount) * gridSize,
                    y: Math.floor(Math.random() * tileCount) * gridSize
                };

                // 确保食物不会出现在蛇身上
                const onSnake = snake.some(segment => segment.x === food.x && segment.y === food.y);
                if (onSnake) {
                    generateFood();
                }
            }

            // 绘制蛇
            function drawSnake() {
                snake.forEach((segment, index) => {
                    // 蛇头
                    if (index === 0) {
                        ctx.fillStyle = '#16a34a'; // 深绿色
                        ctx.fillRect(segment.x, segment.y, gridSize, gridSize);

                        // 蛇眼
                        ctx.fillStyle = 'white';
                        if (dx > 0) { // 向右
                            ctx.fillRect(segment.x + gridSize - 8, segment.y + 5, 3, 3);
                            ctx.fillRect(segment.x + gridSize - 8, segment.y + gridSize - 8, 3, 3);
                        } else if (dx < 0) { // 向左
                            ctx.fillRect(segment.x + 5, segment.y + 5, 3, 3);
                            ctx.fillRect(segment.x + 5, segment.y + gridSize - 8, 3, 3);
                        } else if (dy > 0) { // 向下
                            ctx.fillRect(segment.x + 5, segment.y + gridSize - 8, 3, 3);
                            ctx.fillRect(segment.x + gridSize - 8, segment.y + gridSize - 8, 3, 3);
                        } else if (dy < 0) { // 向上
                            ctx.fillRect(segment.x + 5, segment.y + 5, 3, 3);
                            ctx.fillRect(segment.x + gridSize - 8, segment.y + 5, 3, 3);
                        }
                    }
                    // 蛇身
                    else {
                        // 交替颜色，使蛇看起来有节段感
                        ctx.fillStyle = index % 2 === 0 ? '#22c55e' : '#16a34a';
                        ctx.fillRect(segment.x, segment.y, gridSize, gridSize);
                    }
                });
            }

            // 绘制食物
            function drawFood() {
                ctx.fillStyle = '#ef4444'; // 红色食物
                ctx.fillRect(food.x, food.y, gridSize, gridSize);

                // 食物装饰
                ctx.fillStyle = '#dc2626';
                ctx.beginPath();
                ctx.arc(food.x + gridSize/2, food.y + gridSize/2, gridSize/4, 0, Math.PI * 2);
                ctx.fill();
            }

            // 绘制网格
            function drawGrid() {
                ctx.fillStyle = '#1e293b';
                ctx.fillRect(0, 0, canvas.width, canvas.height);
            }

            // 更新游戏状态
            function update() {
                // 应用下一次的移动方向
                dx = nextDx;
                dy = nextDy;

                // 创建新的蛇头
                const head = {x: snake[0].x + dx, y: snake[0].y + dy};

                // 将新蛇头添加到蛇的前面
                snake.unshift(head);

                // 检查是否吃到食物
                if (head.x === food.x && head.y === food.y) {
                    score += 10 * level;
                    currentScoreEl.textContent = score;

                    // 更新高分
                    if (score > highScore) {
                        highScore = score;
                        highScoreEl.textContent = highScore;
                        localStorage.setItem('snakeHighScore', highScore);
                    }

                    foodEatenInLevel++;

                    // 每吃5个食物升级一次
                    if (foodEatenInLevel >= 5) {
                        level++;
                        levelEl.textContent = level;
                        foodEatenInLevel = 0;

                        // 清除当前游戏循环并以更快的速度重启
                        clearInterval(gameLoop);
                        gameLoop = setInterval(game, 150 - (level * 10));
                    }

                    // 生成新食物
                    generateFood();
                } else {
                    // 如果没吃到食物，移除蛇尾
                    snake.pop();
                }

                // 检查碰撞
                checkCollisions();
            }

            // 检查碰撞
            function checkCollisions() {
                const head = snake[0];

                // 检查是否撞墙
                if (head.x < 0 || head.x >= canvas.width || head.y < 0 || head.y >= canvas.height) {
                    gameOver();
                    return;
                }

                // 检查是否撞到自己
                for (let i = 1; i < snake.length; i++) {
                    if (head.x === snake[i].x && head.y === snake[i].y) {
                        gameOver();
                        return;
                    }
                }
            }

            // 游戏结束
            function gameOver() {
                isGameRunning = false;
                clearInterval(gameLoop);
                finalScoreEl.textContent = score;
                gameOverScreen.classList.remove('hidden');
            }

            // 游戏主循环
            function game() {
                if (!isPaused) {
                    drawGrid();
                    drawFood();
                    update();
                    drawSnake();
                }
            }

            // 开始游戏
            function startGame() {
                initGame();
                startScreen.classList.add('hidden');
                gameOverScreen.classList.add('hidden');

                // 启动游戏循环 (初始速度: 150ms)
                gameLoop = setInterval(game, 150);
            }

            // 暂停游戏
            function pauseGame() {
                if (isGameRunning && !isPaused) {
                    isPaused = true;
                    pauseBtn.classList.add('hidden');
                    resumeBtn.classList.remove('hidden');
                }
            }

            // 继续游戏
            function resumeGame() {
                if (isGameRunning && isPaused) {
                    isPaused = false;
                    resumeBtn.classList.add('hidden');
                    pauseBtn.classList.remove('hidden');
                }
            }

            // 切换全屏模式
            function toggleFullscreen() {
                if (!document.fullscreenElement) {
                    document.documentElement.requestFullscreen().catch(err => {
                        console.log(`全屏错误: ${err.message}`);
                    });
                    fullscreenToggle.innerHTML = '<i class="fa fa-compress text-xl"></i>';
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                        fullscreenToggle.innerHTML = '<i class="fa fa-expand text-xl"></i>';
                    }
                }
            }

            // 键盘控制
            function handleKeydown(e) {
                // 防止页面滚动
                if ([37, 38, 39, 40].includes(e.keyCode)) {
                    e.preventDefault();
                }

                // 方向控制 (防止180度转向)
                switch(e.keyCode) {
                    case 37: // 左箭头
                    case 65: // A键
                        if (dx === 0) { // 只有当当前不是水平移动时才能向左
                            nextDx = -gridSize;
                            nextDy = 0;
                        }
                        break;
                    case 38: // 上箭头
                    case 87: // W键
                        if (dy === 0) { // 只有当当前不是垂直移动时才能向上
                            nextDx = 0;
                            nextDy = -gridSize;
                        }
                        break;
                    case 39: // 右箭头
                    case 68: // D键
                        if (dx === 0) { // 只有当当前不是水平移动时才能向右
                            nextDx = gridSize;
                            nextDy = 0;
                        }
                        break;
                    case 40: // 下箭头
                    case 83: // S键
                        if (dy === 0) { // 只有当当前不是垂直移动时才能向下
                            nextDx = 0;
                            nextDy = gridSize;
                        }
                        break;
                    case 32: // 空格键 (暂停/继续)
                        if (isGameRunning) {
                            isPaused ? resumeGame() : pauseGame();
                        }
                        break;
                    case 13: // 回车键 (开始/重新开始)
                        if (!isGameRunning) {
                            startGame();
                        }
                        break;
                }
            }

            // 事件监听器
            startBtn.addEventListener('click', startGame);
            restartBtn.addEventListener('click', startGame);
            desktopRestartBtn.addEventListener('click', startGame);
            pauseBtn.addEventListener('click', pauseGame);
            resumeBtn.addEventListener('click', resumeGame);
            fullscreenToggle.addEventListener('click', toggleFullscreen);

            // 移动设备触摸控制
            upBtn.addEventListener('click', () => {
                if (dy === 0) {
                    nextDx = 0;
                    nextDy = -gridSize;
                }
            });

            downBtn.addEventListener('click', () => {
                if (dy === 0) {
                    nextDx = 0;
                    nextDy = gridSize;
                }
            });

            leftBtn.addEventListener('click', () => {
                if (dx === 0) {
                    nextDx = -gridSize;
                    nextDy = 0;
                }
            });

            rightBtn.addEventListener('click', () => {
                if (dx === 0) {
                    nextDx = gridSize;
                    nextDy = 0;
                }
            });

            // 键盘控制
            document.addEventListener('keydown', handleKeydown);

            // 初始化高分显示
            highScoreEl.textContent = highScore;

            // 初始绘制
            drawGrid();
        });
    </script>
</body>
</html>